<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Users extends CI_Controller {

    public function index() {
        if (!$this->session->userdata('logged_in')) {
            redirect('/users/login/');
        } else {
            redirect('/expenses/add/');
        }
    }

    public function login() {
        if ($this->input->post('submit')) {
            $username = $this->input->post('username');
            $password = $this->input->post('password');

            $this->load->model('User');
            $user = $this->User->validate($username, $password);

            if ($user) {
                $data = array(
                    'user_id' => $user->id,
                    'name' => $user->name,
                    'username' => $user->username,
                    'logged_in' => true
                );

                $this->session->set_userdata($data);
                
                redirect('/expenses/add/');
            } else {
                $this->session->set_flashdata('important', 'Incorrect email/password combination.');
                redirect('/users/login/');
            }
        } else {
            $data = array(
                'title' => 'Login'
            );

            $this->load->view('header', $data);
            $this->load->view('users_login');
            $this->load->view('footer');
        }
    }

    public function logout() {
        $this->session->sess_destroy();
        $this->session->unset_userdata('logged_in');
        
        $this->session->set_flashdata('warning', 'You have been logged out.');
        redirect('/users/login/');
    }    
    
    public function home() {
        $this->load->model('Expense');

        $expenses = $this->Expense->get_latest();

        $strings = array();

        foreach ($expenses as $expense) {
            $string = array(
                'name' => $expense['name'],
                'item' => $expense['item'],
                'amount' => $expense['amount'],
                'timestamp' => $expense['timestamp'],
                'user_id' => $expense['id']
            );

            $strings[] = $string;
        }

        $data = array(
            'title' => 'Home'
        );

        $this->load->view('header', $data);

        $data = array(
            'strings' => $strings
        );

        $this->load->view('home', $data);
        $this->load->view('footer');
    }

}
